class OpenFile(object):
    def __init__(self,filename,method):
        self.file=open(filename,method)

    def __enter__(self):
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        退出上下文时，将文件关闭
        :param exc_type: 异常类型，with中的代码如果执行出错，会将异常类型传递给exc_type
        :param exc_val: 异常信息，with中的代码如果执行出错，会将异常信息传递给exc_val
        :param exc_tb: 异常溯源，with中的代码如果执行出错，会将异常溯源对象传递给exc_tb
        :return:
        """
        self.file.close()

if __name__ == '__main__':
    with OpenFile("python.txt","r") as f:
        print(f.readlines())

